package com.hyt.it.ogt.ksmonitor.statistics.service.core;

import com.hyt.it.ogt.ksmonitor.statistics.annotations.MonitorStatistics;
import com.hyt.it.ogt.ksmonitor.statistics.service.IMonitorStatisticsSubmitService;
import com.hyt.it.ogt.ksmonitor.statistics.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import static com.hyt.it.ogt.ksmonitor.statistics.constants.MonitorStatisticsConstants.*;

/**
 * @author 朱振宇
 * @since 2022/11/13
 */
@Slf4j
@Aspect
@Order
@Component
@ConditionalOnProperty(value = "ksMonitorStatistics.enabled", havingValue = "true", matchIfMissing = true)
public class KsMonitorStatisticsAspect {

    @Resource
    private IMonitorStatisticsSubmitService iMonitorStatisticsSaveService;

    // 配置织入点
    @Pointcut("execution(* *(..)) && @annotation(statisticsAnnotation)")
    public void statisticsPointCut(MonitorStatistics statisticsAnnotation) {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "statisticsPointCut(statisticsAnnotation)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, MonitorStatistics statisticsAnnotation, Object jsonResult) {
        handleStatistics(joinPoint, statisticsAnnotation, null, jsonResult);
    }

    protected void handleStatistics(final JoinPoint joinPoint, MonitorStatistics statisticsAnnotation, final Exception e, Object jsonResult) {
        try {
            CompletableFuture.runAsync(() -> {
                if(jsonResult == null) {
                    return;
                }
                try {
                    Map<String, Object> resultMap = BeanUtils.convertBeanToMap(jsonResult);
                    if(resultMap.get(DATA) != null) {
                        Map<String, Object> dataMap = BeanUtils.convertBeanToMap(resultMap.get(DATA));
                        if(dataMap.get(statisticsAnnotation.examIdAliasName()) != null && dataMap.get(statisticsAnnotation.candidateIdAliasName()) != null) {
                            iMonitorStatisticsSaveService.addNum(dataMap.get(statisticsAnnotation.examIdAliasName()).toString(), statisticsAnnotation.statisticsType(), dataMap.get(statisticsAnnotation.candidateIdAliasName()).toString(), statisticsAnnotation.isRepeat(), statisticsAnnotation.num());
                        }
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            });
        } catch (Exception exception) {
            log.error("# ==后置通知异常==");
            log.error("# 异常信息:{}", exception.getMessage());
        }
    }

}
